import 'dart:io';
import 'dart:ui';
import 'package:extended_nested_scroll_view/extended_nested_scroll_view.dart';
import 'package:flutter/cupertino.dart'
    hide NestedScrollView, NestedScrollViewState;
import 'package:flutter/material.dart'
    hide NestedScrollView, NestedScrollViewState;
import 'package:flutter/services.dart';
import 'package:test01/okhttp_test/page/personalhomepage/dynamic/my_dynamic_follow_page.dart';
import 'package:test01/okhttp_test/page/personalhomepage/dynamic/my_dynamic_recommend_page.dart';
import 'package:test01/okhttp_test/pojo/attention_pojo.dart';
import 'package:test01/okhttp_test/pojo/rewrite/mytabindicator.dart';
import 'package:test01/okhttp_test/pojo/rewrite/mytabs.dart' as newtab;

import 'package:test01/okhttp_test/pojo/userinfor_pojo.dart';
import 'package:test01/okhttp_test/util/request_http.dart';
import 'package:test01/okhttp_test/util/screen_util.dart';

import '../my_attention_page.dart';
import '../my_fans_page.dart';
import 'custom_appbar.dart';
import 'my_dynamic_edit_data_page.dart';

/*
*
*
* 我的-----动态界面
*
*
* */

class NetScrollHomePage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return ScrollHomePageState();
  }
}

class ScrollHomePageState extends State with SingleTickerProviderStateMixin {
  ScrollController controller = ScrollController();

  ///粉丝数量、关注数量
  GetFollowCounts getFollowCounts = GetFollowCounts();

  ///用户基础信息
  UserBaseInfoDto userBaseInfoDto = UserBaseInfoDto();

  ///关注
  final GlobalKey<DynamicFollowVidoListState> followkeys = GlobalKey();

  ///推荐
  final GlobalKey<DynamicRcommendVidoListState> recommendkeys = GlobalKey();

  ///顶部颜色透明度
  double transparency = 0.0;

  int index;

  void tabControlerListener() {
    if (index != tabController.index) {
      //your code
      index = tabController.index;
    }
  }

  TabController tabController;
  ScrollController scrollController;

  @override
  void initState() {
    tabController = new TabController(length: 2, vsync: this, initialIndex: 0);
    mynumbers();
    controller.addListener(() {
      //获取上拉之后吸顶的百分比
      transparency = controller.position.pixels /
          (MediaQuery.of(context).padding.top + 200 + 48 + 20-(ScreenUtil.instance.statusBarHeight + CustomAppBar.appBarHeight));
      setState(() {});
      //根据tabBar的index判断-----上拉加载更多
      if (controller.position.pixels == controller.position.maxScrollExtent) {
        print("${tabController.index}");
        if (tabController.index == 0) {
          followkeys.currentState.pullUpRefresh();
        }
        if (tabController.index == 1) {
          recommendkeys.currentState.recommendPullUpRefresh();
        }
      }
    });

    super.initState();
  }

  @override
  void dispose() {
    tabController.removeListener(tabControlerListener);
    tabController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      /// 处理滑动
      body: userBaseInfoDto.uid == null ? Container() :Container(
        child: Stack(
          children: <Widget>[
            buildNestedScrollView(),
        Offstage(
          offstage:transparency>=0?false:true,
          child: Container(
            height: ScreenUtil.instance.statusBarHeight + CustomAppBar.appBarHeight,
            padding: EdgeInsets.only(left: 16, right: 16),
            color: Colors.white.withOpacity(transparency),
            child: Row(children: <Widget>[
              GestureDetector(
                onTap: () {
                  Navigator.of(context).pop();
                },
                child: Icon(
                  Icons.arrow_back_ios,
                  size: 18.86,
                  color: Colors.black.withOpacity(transparency),
                ),
              ),
             Container(
               alignment: Alignment.center,
               width: MediaQuery.of(context).size.width-40-40,
               child: Text(userBaseInfoDto.nickName,style: TextStyle(color: Colors.black.withOpacity(transparency)),),
             ),
              Spacer(),
              Container(
                child: Icon(
                  Icons.add_photo_alternate_outlined,
                  size: 17.74,
                  color: Colors.black.withOpacity(transparency),
                ),
              )
            ]),
          ),
        ),

          ],
        ),


      ),
    );
  }

  ///构建滑动布局
  NestedScrollView buildNestedScrollView() {
    return NestedScrollView(
      controller: controller,
      pinnedHeaderSliverHeightBuilder: () {
        return ScreenUtil.instance.statusBarHeight + CustomAppBar.appBarHeight;
      },

      headerSliverBuilder: (BuildContext context, bool b) {
        return <Widget>[
          SliverToBoxAdapter(
            child: vague(),
          ),

        ];
      },

      ///定义tab的Key值
      innerScrollPositionKeyBuilder: () {
        String index = 'Tab';
        index += tabController.index.toString();
        return Key(index);
      },

      ///主体部分
      body: TabBarViewLists(),
    );
  }

  ///获取我的界面用户信息
  mynumbers() async {
    //获取关注数、粉丝数、点赞数
    getFollowCounts =
        await getFollowCount(interface: "/appuser/web/user/getFollowCount");
    //获取用户基础信息
    userBaseInfoDto =
        await getUserBaseInfo(interface: "/ucenter/web/user/getUserBaseInfo");
    print("---------------用户数据-------------------------");
    setState(() {});
  }

  ///高斯模糊
  Widget vague() {
    ///沉侵式状态栏
    if (Platform.isAndroid) {
      SystemUiOverlayStyle systemUiOverlayStyle =
          SystemUiOverlayStyle(statusBarColor: Colors.transparent);
      SystemChrome.setSystemUIOverlayStyle(systemUiOverlayStyle);
    }
    return Container(
        // margin: EdgeInsets.only(top:(MediaQuery.of(context).padding.top)),
        child: Stack(
      alignment: Alignment.center,
      children: <Widget>[
        Container(
          width: MediaQuery.of(context).size.width,
          height: MediaQuery.of(context).padding.top + 200 + 48 + 20,
          child: Image.network(
            userBaseInfoDto.avatarUri,
            fit: BoxFit.cover,
          ),
        ),
        ClipRect(
          child: BackdropFilter(
            filter: ImageFilter.blur(sigmaX: 28, sigmaY: 28),
            child: Container(
                width: MediaQuery.of(context).size.width,
                height: MediaQuery.of(context).padding.top + 200 + 48 + 20,
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    SizedBox(
                      height: MediaQuery.of(context).padding.top,
                    ),
                    topReturn(),
                    //头像
                    headPortrait(),
                    //昵称
                    nickName(),
                    //ID
                    userId(),
                    //宣言
                    userAutograph(),
                    //粉丝信息
                    fansNumber(),
                  ],
                )),
          ),
        ),
      ],
    ));
  }

  ///顶部返回
  Widget topReturn() {
    return Container(
      height: 48,
      margin: EdgeInsets.only(left: 16, right: 16),
      child: Row(children: <Widget>[
        GestureDetector(
          onTap: () {
            Navigator.of(context).pop();
          },
          child: Icon(
            Icons.arrow_back_ios,
            size: 18.86,
            color: Colors.black,
          ),
        ),
        Spacer(),
        Container(
          child: Icon(
            Icons.add_photo_alternate_outlined,
            size: 17.74,
            color: Colors.black,
          ),
        )
      ]),
    );
  }

  ///头像
  Widget headPortrait() {
    return Container(
      margin: EdgeInsets.only(top: 5),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[
          SizedBox(
            width: 16,
          ),
          Container(
            width: 71,
            height: 71,
            child: CircleAvatar(
                radius: 71,
                backgroundImage: NetworkImage(userBaseInfoDto.avatarUri)),
          ),
          Spacer(),
          Container(
            child: GestureDetector(
              onTap: (){
                print("-------------编辑用户资料---------------");
                Navigator.push(context, MaterialPageRoute(builder: (context) {
                  return EditDataPage();
                }));
              },
              child: Container(
                width: MediaQuery.of(context).size.width - 15.5 - 287.5,
                height: 28,
                alignment: Alignment.center,
                decoration: BoxDecoration(
                  border:
                  Border.all(width: 0.5, color: Colors.black.withOpacity(0.3)),
                  borderRadius: BorderRadius.circular(14),
                ),
                child: Text(
                  "编辑资料",
                  style: TextStyle(fontSize: 12, color: Colors.black),
                ),
              ),
            ),
          ),
          SizedBox(
            width: 15.5,
          ),
        ],
      ),
    );
  }

  ///昵称
  Widget nickName() {
    return Container(
      margin: EdgeInsets.only(left: 16, top: 16),
      child: Text(
        userBaseInfoDto.nickName,
        style: TextStyle(fontSize: 18, color: Color.fromRGBO(17, 17, 17, 0.85)),
      ),
    );
  }

  ///用户Id
  Widget userId() {
    return Container(
      margin: EdgeInsets.only(left: 16, top: 12),
      child: Text(
        "ID:${userBaseInfoDto.uid}",
        style: TextStyle(fontSize: 12, color: Color.fromRGBO(51, 51, 51, 1)),
      ),
    );
  }

  ///签名
  Widget userAutograph() {
    return Container(
      width: MediaQuery.of(context).size.width - 16 - 104,
      height: 16.5,
      margin: EdgeInsets.only(left: 16, top: 6),
      child: Text(
        userBaseInfoDto.description ?? "",
        style: TextStyle(fontSize: 12, color: Color.fromRGBO(51, 51, 51, 1)),
        maxLines: 1,
        overflow: TextOverflow.ellipsis,
      ),
    );
  }

  ///粉丝信息
  Widget fansNumber() {
    return Container(
      height: 44,
      margin: EdgeInsets.only(left: 16),
      child: Row(
        children: <Widget>[
          //关注
          GestureDetector(
            onTap: () {
              Navigator.push(context, MaterialPageRoute(builder: (context) {
                return MyAttentionPage();
              }));
            },
            child: Container(
              width: 85,
              alignment: Alignment.centerLeft,
              child: Column(
                children: <Widget>[
                  Text(
                    "${getFollowCounts.followingCount}",
                    style: TextStyle(fontSize: 18),
                  ),
                  SizedBox(
                    height: 2.5,
                  ),
                  Text(
                    "关注",
                    style: TextStyle(
                        fontSize: 12, color: Colors.black.withOpacity(0.5)),
                  )
                ],
              ),
            ),
          ),

          //粉丝数量
          GestureDetector(
            onTap: () {
              Navigator.push(context, MaterialPageRoute(builder: (context) {
                return FansPage();
              }));
            },
            child: Container(
              width: 85,
              alignment: Alignment.centerLeft,
              child: Column(
                children: <Widget>[
                  Text(
                    "${getFollowCounts.followerCount}",
                    style: TextStyle(fontSize: 18),
                  ),
                  SizedBox(
                    height: 2.5,
                  ),
                  Text(
                    "粉丝",
                    style: TextStyle(
                        fontSize: 12, color: Colors.black.withOpacity(0.5)),
                  )
                ],
              ),
            ),
          ),

          //获赞数量
          Container(
            width: 85,
            alignment: Alignment.centerLeft,
            child: Column(
              children: <Widget>[
                Text(
                  "${getFollowCounts.laudedCount}",
                  style: TextStyle(fontSize: 18),
                ),
                SizedBox(
                  height: 2.5,
                ),
                Text(
                  "获赞",
                  style: TextStyle(
                      fontSize: 12, color: Colors.black.withOpacity(0.5)),
                )
              ],
            ),
          ),
        ],
      ),
    );
  }

  ///TabBar切换标签
  newtab.TabBar buildTabBar() {
    return newtab.TabBar(
      controller: tabController,
      tabs: <Widget>[
        Text("关注"),
        Text("推荐"),
      ],
      indicatorColor: Colors.red,
      indicator: MyUnderlineTabIndicator(
          borderSide: BorderSide(width: 2.0, color: Colors.red),
          insets: EdgeInsets.only(
            bottom: 1,
          )),

      ///选中标签的样式以及颜色
      labelStyle: TextStyle(fontSize: 18),
      labelColor: Colors.black,
      unselectedLabelStyle: TextStyle(fontSize: 16),

      ///未选中标签样式以及颜色
      unselectedLabelColor: Colors.black.withOpacity(0.5),
    );
  }

  ///TabelBar+TabBarView
  Widget TabBarViewLists() {
    return Container(
      child: Column(
        children: <Widget>[
          Container(
            height: 48,
            color: Colors.white,
            child: buildTabBar(),
          ),
          Expanded(child: buildTabBarView()),
        ],
      ),
    );
  }

  ///下部分界面
  TabBarView buildTabBarView() {
    return TabBarView(
      controller: tabController,
      children: <Widget>[
        DynamicFollowVidoList(
          key: followkeys,
          tabKey: Key('Tab0'),
          oldDemo: true,
        ),
        DynamicRcommendVidoList(
          tabKey: Key('Tab1'),
          oldDemo: true,
          key: recommendkeys,
        ),
      ],
    );
  }
}

class StickyTabBarDelegate extends SliverPersistentHeaderDelegate {
  final newtab.TabBar child;

  StickyTabBarDelegate({@required this.child});

  @override
  Widget build(
      BuildContext context, double shrinkOffset, bool overlapsContent) {
    return Column(
      children: <Widget>[
        Container(
          height: 44,
          color: Colors.white,
          child: this.child,
        ),
      ],
    );
  }

  @override
  double get maxExtent => this.child.preferredSize.height;

  @override
  double get minExtent => this.child.preferredSize.height;

  @override
  bool shouldRebuild(SliverPersistentHeaderDelegate oldDelegate) {
    return true;
  }
}
